package com.netease.nim.demo.team.activity;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.NewActionHelp;
import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.dao.AddressBookInfoDao;
import com.google.gson.reflect.TypeToken;
import com.mywork.WorkUIKit;
import com.netease.nim.demo.base.YXBaseActivity;
import com.netease.nim.demo.common.adapter.TAdapterDelegate;
import com.netease.nim.demo.common.adapter.TViewHolder;
import com.netease.nim.demo.contact.cache.ContactDataCache;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.contact.cache.TeamMemberInfoCache;
import com.netease.nim.demo.main.fragment.ContactsFragment;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.RoamingMessageActivity;
import com.netease.nim.demo.team.adapter.TeamMemberAdapter;
import com.netease.nim.demo.team.adapter.TeamMemberAdapter.TeamMemberItem;
import com.netease.nim.demo.team.ui.TeamInfoGridView;
import com.netease.nim.demo.team.viewholder.TeamMemberHolder;
import com.netease.nim.demo.team.viewholder.TeamMemberHolder.ItemClickListener;
import com.netease.nim.demo.util.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw.activity.ChatPersonalInfoActivity;
import com.shwread.android.qysw.activity.NewInteractionCreateTeamChMActivity;
import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.dialog.ClearChatRecordDialog;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.dialog.RemoveTeamMemberDialog;
import com.shwread.android.ui.dialog.RemoveTeamMemberDialog.RemoveListener;
import com.shwread.android.ui.dialog.SimpleListener;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import logic.bean.GroupBean;
import logic.bean.TeamMemberX;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.GroupDao;
import logic.util.NetworkUtil;
import logic.util.Utils;


/**
 * 群资料页(TARGET_CREATE_NORMAL_TEAM) / 创建群(TARGET_TEAM_INFO),包括普通群和固定群
 * Created by huangjun on 2015/3/3.
 */
public class TeamInfoActivity
        extends
        YXBaseActivity
        implements
        OnClickListener,
        TAdapterDelegate,
        TeamMemberAdapter.RemoveMemberCallback,
        TeamMemberAdapter.AddMemberCallback {
    public static final int TARGET_TEAM_INFO = 0x00;
    public static final int TARGET_CREATE_NORMAL_TEAM = 0x01;
    public static final int REQUEST_CODE = 0x04;
    public static final int ADD_REQUEST_CODE = 0x05;
    public static final int CLEAR_HISTORY_CODE = 0x06;
    public static final int GET_MEMBER_CODE = 0x07;
    public static final String RESULT_EXTRA_REASON = "RESULT_EXTRA_REASON";
    public static final String RESULT_EXTRA_REASON_DISMISS = "RESULT_EXTRA_REASON_DISMISS";
    public static final String RESULT_EXTRA_REASON_QUIT = "RESULT_EXTRA_REASON_QUIT";
    public static final String RESULT_EXTRA_REASON_CREATE = "RESULT_EXTRA_REASON_CREATE";
    public static final String RESULT_EXTRA_DATA = "RESULET_EXTRA_DATA";
    public static final String RESULT_EXTRA_REASON_CLEAR = "RESULT_EXTRA_REASON_CLEAR";
    // constant
    private static final String TAG = "TeamInfoActivity";
    private static final String EXTRA_ID = "EXTRA_ID";
    private static final String EXTRA_FIRST_MEMBER_ACCOUNT = "EXTRA_FIRST_MEMBER_ACCOUNT";
    private static final String EXTRA_TARGET = "EXTRA_TARGET";
    public static int isTeamHeader = 0;
    // adapter & data source
    private TeamMemberAdapter adapter;

    private String teamId;

    private Team team;

    //	private TeamMemberX                            creator                     = new TeamMemberX();

    private List<TeamMemberX> memberAccounts;

    private List<TeamMemberAdapter.TeamMemberItem> dataSource;

    // view
    private TextView teamNameTextView;

    private TeamInfoGridView gridView;

    private int teamCapacity = 50;                           // 群人数上限，暂定

    private int target = TARGET_TEAM_INFO;

    private TextView tvTitle;

    private Button btnBack;

    private TextView tvTeamName;
    private TextView tvCount;

    private View teamNameLayout;
    private View queryHistoryLayout;
    private View clearHistoryLayout;

    private Context context;

    private RelativeLayout expandLL;
    private LinearLayout teamNameLinearLayout;
    private RelativeLayout teamDismissLayout;
    private FrameLayout gridFly;
    private ImageView expandImg, changeNameImg;
    private boolean hasClearHistory;

    /**
     * 启动群资料页
     *
     * @param context 调用方Activity
     * @param id      讨论组ID
     */
    public static void startForTeamInfo(Context context, String id) {
        start(context, id, TARGET_TEAM_INFO);
    }

    private static void start(Context context, String id, int target) {
        Intent intent = new Intent();
        if (!TextUtils.isEmpty(id)) {
            intent.putExtra(target == TARGET_TEAM_INFO ? EXTRA_ID : EXTRA_FIRST_MEMBER_ACCOUNT, id);
        }
        intent.putExtra(EXTRA_TARGET, target);
        intent.setClass(context, TeamInfoActivity.class);
        ((Activity) context).startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * ************************ TAdapterDelegate **************************
     */

    @Override
    public int getViewTypeCount() {
        return 1;
    }

    @Override
    public Class<? extends TViewHolder> viewHolderAtPosition(int position) {
        return TeamMemberHolder.class;
    }

    @Override
    public boolean enabled(int position) {
        return false;
    }

    /**
     * ***************************** Life cycle *****************************
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        setContentView(R.layout.team_info_activity);
        setContentView(R.layout.new_interaction_center_team_info_activity);
        context = this;
        parseIntentData();
        initAdapter();
        findViews();
        loadTeamInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isTeamHeader = 0;
    }

    private void getTeamHeader() {
        //		for (TeamMemberAdapter.TeamMemberItem item : dataSource)
        //		{
        //			if (item.getTeamRole() == 3 && Const.UserAccId.equals(item.getAccount()))
        //			{
        //				isTeamHeader = 1;
        //			}
        //		}
        for (TeamMemberX account : memberAccounts) {
            if (account.getTeamRole() == 3 && Const.UserAccId.equals(account.getAccId())) {
                isTeamHeader = 1;
            }
        }
        if (isTeamHeader == 1) {
            teamNameLayout.setOnClickListener(this);
        } else {
            teamDismissLayout.setVisibility(View.GONE);
            changeNameImg.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        if (requestCode == ADD_REQUEST_CODE && null != data) {
            addTeamMembers(data.getStringExtra(DefaultConsts.TEAM_ID_LIST));
        }
        if (requestCode == TeamNicknameActivity.REQ_CODE_TEAM_NAME && null != data) {
            ContactsFragment.UPDATE_NICK_NAME = data.getStringExtra(TeamNicknameActivity.EXTRA_NAME);
            modifyTeamName(data.getStringExtra(TeamNicknameActivity.EXTRA_NAME));
            setResult(RESULT_OK, data);
        }
    }

    private void addTeamMembers(String ids) {
        NewActionHelp.inviteMember(this, teamId, team.getName(), ids, "", new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Utils.showToast(TeamInfoActivity.this, "邀请成功");
                TeamMemberInfoCache.getInstance().removeTeamMember(teamId);
                queryTeamInfo();
                requestMembers();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Utils.showToast(TeamInfoActivity.this, "添加失败");
            }
        });
    }

    private void parseIntentData() {
        teamId = getIntent().getStringExtra(EXTRA_ID);
        target = getIntent().getIntExtra(EXTRA_TARGET, TARGET_TEAM_INFO);
    }

    private void loadTeamInfo() {
        Team t = TeamDataCache.getInstance().getTeamById(teamId);
        if (t != null) {
            updateTeamInfo(t);
        } else {
            queryTeamInfo();
        }
    }

    private void queryTeamInfo() {
        NIMClient.getService(TeamService.class).queryTeam(teamId).setCallback(new RequestCallback<Team>() {
            @Override
            public void onSuccess(Team t) {
                TeamDataCache.getInstance().addOrUpdateTeam(t);
                updateTeamInfo(t);
            }

            @Override
            public void onFailed(int code) {
                onGetTeamInfoFailed("" + code);
            }

            @Override
            public void onException(Throwable exception) {
                onGetTeamInfoFailed(exception.getMessage().toString());
            }
        });
    }

    private void updateTeamInfo(Team t) {
        if (t == null) {
            return;
        }
        team = t;
        tvTeamName.setText(!TextUtils.isEmpty(t.getName()) ? t.getName() : "");

        requestMembers();
        //		creator.setAccId(team.getCreator());
    }

    private void onGetTeamInfoFailed(String errorMsg) {
        Toast.makeText(this, getString(R.string.team_not_exist) + ", errorMsg=" + errorMsg, Toast.LENGTH_SHORT).show();
        finish();
    }

    private void initAdapter() {
        memberAccounts = new ArrayList<TeamMemberX>();
        dataSource = new ArrayList<TeamMemberAdapter.TeamMemberItem>();
        adapter = new TeamMemberAdapter(this, dataSource, this, this, this);
    }

    private void findViews() {
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setVisibility(View.VISIBLE);
        tvTitle.setText(getResources().getString(R.string.team_info_title));
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        gridFly = (FrameLayout) findViewById(R.id.new_interaction_center_team_info_members_grid_ll);
        gridView = (TeamInfoGridView) findViewById(R.id.new_interaction_center_team_info_members_grid_view);
        tvCount = (TextView) findViewById(R.id.new_interaction_center_team_info_count);
        teamNameLayout = findViewById(R.id.new_interaction_center_team_name_layout);
        expandLL = (RelativeLayout) findViewById(R.id.new_interaction_center_team_info_expand_ll);
        expandLL.setOnClickListener(this);
        queryHistoryLayout = findViewById(R.id.new_interaction_center_team_query_layout);
        queryHistoryLayout.setOnClickListener(this);
        clearHistoryLayout = findViewById(R.id.new_interaction_center_team_clear_layout);
        clearHistoryLayout.setOnClickListener(this);
        teamDismissLayout = (RelativeLayout) findViewById(R.id.dismiss_team_ray);
        tvTeamName = (TextView) findViewById(R.id.new_interaction_center_team_info_name_content_tv);
        changeNameImg = (ImageView) findViewById(R.id.new_interaction_center_team_info_change_name_img);
        expandImg = (ImageView) findViewById(R.id.new_interaction_center_team_info_expand_img);
        teamNameLinearLayout = (LinearLayout) findViewById(R.id.new_interaction_center_team_info_change_name_ll);
        tvTeamName.setText((team != null && !TextUtils.isEmpty(team.getName())) ? team.getName() : "");
        gridView.setSelector(R.color.common_transparent);
        gridView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == 0) {
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        gridView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP && adapter.getMode() == TeamMemberAdapter.Mode.DELETE) {
                    adapter.setMode(TeamMemberAdapter.Mode.NORMAL);
                    adapter.notifyDataSetChanged();
                    return true;
                }
                return false;
            }
        });
        adapter.setOutView(gridFly);
        adapter.setOutViewG(gridView);
        gridView.setAdapter(adapter);
        adapter.setItemClickListener(new ItemClickListener() {
            @Override
            public void onLongClick(TeamMemberItem item) {
                if (null != item && item.getTeamRole() != 3) {
                    showRemoveDialog(item);
                }
            }

            @Override
            public void onClick(TeamMemberItem item) {
                if (!NetworkUtil.isNetAvailable(context)) {
                    new NoNetDialog(context).show();
                    return;
                } else {
                    AddressBookInfoDao addressBookInfoDao = AddressBookInfoDao.getInstance(context);

                    if (WorkUIKit.getUser().getAccount().equals(item.getAccount()) || addressBookInfoDao.getById(item.getAccount()) != null) {
                        Intent personalInfoIntent = new Intent(TeamInfoActivity.this, ChatPersonalInfoActivity.class);
                        AddressBookInfo addressBookInfo = (AddressBookInfo) addressBookInfoDao.getById(WorkUIKit.getUser().getAccount().equals(item.getAccount()) ? WorkUIKit.getUser().getAccount() : item.getAccount());
                        personalInfoIntent.putExtra("contactInfo", (Serializable) addressBookInfo);
                        GroupDao groupDao = GroupDao.getInstance(context);
                        GroupBean groupBean = groupDao.getById(addressBookInfo.getGroupId());
                        personalInfoIntent.putExtra("groupName", groupBean.getName());//mGroupData.get(groupPosition).getName()
                        context.startActivity(personalInfoIntent);
                        return;

                    }


                    //					if (item != null && !item.getAccount().substring(0, 11).equals(NewActionHelp.getAccount()))
                    if (item != null && !item.getAccount().equals(Const.UserAccId)) {
                        //						Intent intent = new Intent();
                        //						intent.putExtra(DefaultConsts.TO_P2P_PAGE_TAG, DefaultConsts.TO_P2P_PAGE_FROM_TEAM_INFO);
                        //						String str;//用于聊天页面的标题头显示昵称
                        //						if (Utils.isEmpty(item.getNickName()))
                        //						{
                        //							str = item.getAccount().substring(0, 11);
                        //						}
                        //						else
                        //						{
                        //							str = item.getNickName();
                        //						}
                        //						intent.putExtra(DefaultConsts.TO_P2P_PAGE_INFO, str);
                        P2PMessageActivity.start(context, item.getAccount());
                    }
                }
            }
        });
    }

    private void showRemoveDialog(final TeamMemberItem item) {
        RemoveTeamMemberDialog dialog = new RemoveTeamMemberDialog(this);
        dialog.setListener(new RemoveListener() {
            @Override
            public void onRemove() {
                onRemoveMember(item.getAccount());
            }
        });
        dialog.show();
    }

    public void dismissTeam(View v) {
        NewActionHelp.dismissTeam(this, teamId, new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                TeamMemberInfoCache.getInstance().removeTeamMember(teamId);
                //				Utils.showToast(TeamInfoActivity.this, "解散群成功");
                NIMClient.getService(TeamService.class).dismissTeam(teamId).setCallback(new RequestCallback<Void>() {
                    @Override
                    public void onException(Throwable exception) {
                        String errorMsg = "dismiss Team exception :" + exception.getMessage();
                        Toast.makeText(TeamInfoActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        LogUtil.e(TAG, errorMsg);
                    }

                    @Override
                    public void onFailed(int code) {
                        String errorMsg = "dismiss Team failed :" + code;
                        Toast.makeText(TeamInfoActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        LogUtil.e(TAG, errorMsg);
                    }

                    @Override
                    public void onSuccess(Void arg0) {
                        hasClearHistory = false;
                        Utils.showToast(TeamInfoActivity.this, "解散群成功");
                        TeamDataCache.getInstance().removeTeamMember(teamId);
                        TeamDataCache.getInstance().removeTeam(teamId);
                        ContactDataCache.getInstance().clearBuddyCache();
                        setResult(Activity.RESULT_OK, new Intent().putExtra(RESULT_EXTRA_REASON, RESULT_EXTRA_REASON_QUIT));
                        finish();
                    }
                });
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Logger.e(responseString);
                Utils.showToast(TeamInfoActivity.this, "解散群失败");
            }
        });
    }

    /**
     * *************************** 加载&变更数据源 ********************************
     */
    private void requestMembers() {
        gridView.setVisibility(View.GONE);
        memberAccounts.clear();

        List<TeamMemberX> list = TeamMemberInfoCache.getInstance().getTeamMember(teamId);
        if (null != list && !list.isEmpty()) {
            gridView.setVisibility(View.VISIBLE);
            addMember(list, true);
        } else {
            NewActionHelp.qryMemberListByTeamId(context, teamId, new ObjectHttpResponseHandler<List<TeamMemberX>>() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    String errorMsg = "request team member list failed :" + statusCode;
                    Toast.makeText(TeamInfoActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    LogUtil.e(TAG, errorMsg);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, List<TeamMemberX> object, String responseString) {
                    if (object == null || object.isEmpty()) {
                        String errorMsg = "queryMemberList empty";
                        LogUtil.e(TAG, errorMsg);
                        Toast.makeText(TeamInfoActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    TeamMemberInfoCache.getInstance().addTeam(teamId, object);
                    TeamMemberInfoCache.getInstance().add(object);
                    gridView.setVisibility(View.VISIBLE);
                    addMember(object, true);
                }

                @Override
                public Type getType() {
                    return new TypeToken<List<TeamMemberX>>() {
                    }.getType();
                }
            });
        }
    }

    private void addMember(List<TeamMemberX> accounts, boolean clear) {
        if (accounts == null || accounts.isEmpty()) {
            return;
        }
        memberAccounts.clear();
        memberAccounts.addAll(accounts);
        // sort
        Collections.sort(this.memberAccounts, new Comparator<TeamMemberX>() {
            @Override
            public int compare(TeamMemberX l, TeamMemberX r) {
                //				if (creator.getAccId().equals(l.getAccId())) { return -1; }
                //				if (creator.getAccId().equals(r.getAccId())) { return 1; }
                //				return l.getAccId().compareTo(r.getAccId());
                return r.getTeamRole() > l.getTeamRole() ? 1 : -1;
            }
        });

        updateDataSource();
    }

    private void updateDataSource() {
        dataSource.clear();
        getTeamHeader();
        // add item
        if (isTeamHeader == 1) {
            dataSource.add(new TeamMemberAdapter.TeamMemberItem(TeamMemberAdapter.TeamMemberItemTag.ADD, null, null, null, null, null, null, 0));
        }
        // member item
        String identity = null;

        for (TeamMemberX account : memberAccounts) {
            //			if (account.getTeamRole() == 3) creator = account;
            identity = account.getTeamRole() == 3 ? TeamMemberHolder.OWNER : null;
            if (Utils.isNotEmpty(account.getStaffName())) {
                dataSource.add(new TeamMemberAdapter.TeamMemberItem(TeamMemberAdapter.TeamMemberItemTag.NORMAL, teamId, account.getAccId(), identity, account.getHeadImage(), account.getNickName(), account.getStaffName(), account.getTeamRole()));
            } else {
                dataSource.add(new TeamMemberAdapter.TeamMemberItem(TeamMemberAdapter.TeamMemberItemTag.NORMAL, teamId, account.getAccId(), identity, account.getHeadImage(), account.getNickName(), account.getStaffName(), account.getTeamRole()));
            }
        }
        if (isTeamHeader == 1) {
            tvCount.setText(String.format("群成员(%s人)", String.valueOf(dataSource.size() - 1)));
        } else {
            tvCount.setText(String.format("群成员(%s人)", String.valueOf(dataSource.size())));
        }
        // refresh
        adapter.notifyDataSetChanged();
    }

    /**
     * ******************************* Action *********************************
     */

    private void removeMember(String account) {
        memberAccounts.remove(account);
        for (TeamMemberAdapter.TeamMemberItem item : dataSource) {
            if (account.equals(item.getAccount())) {
                dataSource.remove(item);
                break;
            }
        }
        tvCount.setText(String.format("群成员(%s人)", String.valueOf(dataSource.size() - 1)));
        adapter.notifyDataSetChanged();
    }

    /**
     * 邀请群成员
     */
    @Override
    public void onAddMember() {
        Intent intent = new Intent(this, NewInteractionCreateTeamChMActivity.class);
        intent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_CHOSE_MUNBER);
        ArrayList<String> accIdList = new ArrayList<>();
        for (TeamMemberX memberAccount : memberAccounts) {
            accIdList.add(memberAccount.getAccId());
        }
        intent.putExtra("accIdList", accIdList);
        startActivityForResult(intent, ADD_REQUEST_CODE);
    }

    /**
     * 移除群成员
     */
    @Override
    public void onRemoveMember(final String account) {
        NewActionHelp.kickMember(this, teamId, account, new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                TeamMemberInfoCache.getInstance().removeTeamMemberByAccid(teamId, account);
                removeMember(account);
                Toast.makeText(TeamInfoActivity.this, R.string.remove_member_success, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Toast.makeText(TeamInfoActivity.this, R.string.remove_member_failed, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void modifyTeamName(final String name) {
        NewActionHelp.updateTeam(this, teamId, name, new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Utils.showToast(context, "修改成功");
                tvTeamName.setText(name);
                //TODO

                NIMClient.getService(TeamService.class).queryTeam(teamId).setCallback(new RequestCallback<Team>() {
                    @Override
                    public void onSuccess(Team team) {
                        if (team != null) {
                            TeamDataCache.getInstance().addOrUpdateTeam(team);
                        }
                    }

                    @Override
                    public void onFailed(int code) {
                    }

                    @Override
                    public void onException(Throwable exception) {
                    }
                });
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Utils.showToast(context, "修改失败");
            }
        });
    }

    /**
     * ******************************* Event *********************************
     */

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.new_interaction_center_team_name_layout:
                TeamNicknameActivity.start(this, tvTeamName.getText().toString().trim());
                break;
            case R.id.new_interaction_center_team_query_layout:
                RoamingMessageActivity.start(this, teamId, SessionTypeEnum.Team);
                break;
            case R.id.new_interaction_center_team_clear_layout:
                clearHistory();
                break;
            case R.id.common_header_back:
                onBackPressed();
                isTeamHeader = 0;
                finish();
                break;
            case R.id.new_interaction_center_team_info_expand_ll:
                if (gridView.getChildCount() > 8) {
                    if (gridFly.getHeight() <= adapter.gridInitHeight) {
                        startAnimation(gridFly, gridView.getHeight() + gridFly.getPaddingBottom() + gridFly.getPaddingTop());
                        startImageOpneRotateAnim();
                    } else {
                        startAnimation(gridFly, adapter.gridInitHeight);
                        startImageCloseRotateAnim();
                    }
                }
                break;
        }
    }

    private void clearHistory() {
        new ClearChatRecordDialog(this, new SimpleListener() {
            @Override
            public void ok() {
                // 删除与某个聊天对象的全部消息记录
                NIMClient.getService(MsgService.class).clearChattingHistory(teamId, SessionTypeEnum.Team);
                Utils.showToast(TeamInfoActivity.this, "已清空聊天记录");
                hasClearHistory = true;
            }
        }).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && adapter.switchMode()) {
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (adapter.switchMode()) {
            return;
        }
        if (hasClearHistory) {
            setResult(Activity.RESULT_OK, new Intent().putExtra(RESULT_EXTRA_REASON, RESULT_EXTRA_REASON_CLEAR));
        }
        super.onBackPressed();
    }

    @SuppressLint("NewApi")
    private void startAnimation(final View v, int endHeight) {
        final LayoutParams params = (LayoutParams) v.getLayoutParams();
        if (android.os.Build.VERSION.SDK_INT > 10) {
            ValueAnimator animation = ValueAnimator.ofInt(v.getHeight(), endHeight);
            animation.setDuration(400);
            animation.addUpdateListener(new AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    int height = Integer.parseInt(animation.getAnimatedValue().toString());
                    params.height = height;
                    v.setLayoutParams(params);
                }
            });
            animation.setInterpolator(new DecelerateInterpolator(2.0f));
            animation.start();
        }
    }

    private void startImageCloseRotateAnim() {
        Animation rotate = AnimationUtils.loadAnimation(this, R.anim.team_expand_totate_close);
        rotate.setDuration(400);
        rotate.setInterpolator(new DecelerateInterpolator(2.0f));
        rotate.setRepeatCount(0);
        rotate.setFillAfter(true);
        expandImg.startAnimation(rotate);
    }

    private void startImageOpneRotateAnim() {
        Animation rotate = AnimationUtils.loadAnimation(this, R.anim.team_expand_totate_open);
        rotate.setDuration(400);
        rotate.setInterpolator(new DecelerateInterpolator(2.0f));
        rotate.setRepeatCount(0);
        rotate.setFillAfter(true);
        expandImg.startAnimation(rotate);
    }

}
